<script setup>
import { computed, reactive, ref } from 'vue';
import { resetPassword, sendSms } from '@/api/user.js';
import { useGlobalAbility } from '@/mixins/getGlobalAbility.js';
import { useRouter } from 'vue-router';

const { $message } = useGlobalAbility();
const router = useRouter();

const form = reactive({
  account: '', // 账号
  password: '', // 密码
  identifyingCode: '', // 验证码
  secondPassword: '', // 密码二次确认
});
const accountError = ref(false); // 账号报错
const identifyingCodeError = ref(false); // 验证码报错
const passwordError = ref(false); // 密码报错
const secondPasswordError = ref(false);
// 设置输入框输入报错取消
function setInputError(code) {
  switch (code) {
    case 'account':
      accountError.value = false;
      break;
    case 'password':
      passwordError.value = false;
      break;
    case 'identifyingCode':
      identifyingCodeError.value = false;
      break;
    case 'secondPassword':
      secondPasswordError.value = false;
      break;
  }
}
const phoneRex = /^1[3-9][0-9]{9}$/;
const sendCodeAgain = ref(true); // 是否可以再次发送验证码
const codeWord = ref('获取验证码'); // 发送验证码的文字
let uuid = '';
// 校验账户信息
function checkAccount() {
  if (form.account === '') {
    $message.error('手机号为空，请输入手机号！');
    accountError.value = true;
    return false;
  }
  if (!phoneRex.test(form.account)) {
    $message.error('手机号输入错误，请重新输入！');
    accountError.value = true;
    return false;
  }
  return true;
}
// 发送验证码
async function sendCode() {
  if (!checkAccount()) {
    return false;
  }
  if (sendCodeAgain.value) {
    let seconds = 60;
    sendCodeAgain.value = false;
    const timer = setInterval(function () {
      seconds -= 1; // 每秒减去1
      codeWord.value = `${seconds}后重新发送`;

      if (seconds <= 0) {
        clearInterval(timer); // 时间到达后清除定时器
        codeWord.value = '重新发送'; // 更新显示文本
        sendCodeAgain.value = true;
      }
    }, 1000);
  }
  const returnData = await sendSms({ userName: form.account, uuid, type: 'reset' });
  console.log(returnData);
  if (returnData?.code !== 200) {
    $message.error(returnData?.msg);
  } else {
    uuid = returnData?.data?.uuid;
  }
}

// 校验

// 手机号验证规则
const validatePhone = () => {
  if (!form.account) {
    $message.error('手机号为空，请输入手机号！');
    accountError.value = true;
  } else if (!/^1[3-9]\d{9}$/.test(form.account)) {
    $message.error('手机号输入错误，请重新输入！');
    accountError.value = true;
  } else {
    accountError.value = false;
  }
};
// 验证码验证规则
const validateSmsCode = () => {
  if (!form.identifyingCode) {
    identifyingCodeError.value = true;
    $message.error('验证码为空，请输入验证码！');
  } else if (!/^\d{6}$/.test(form.identifyingCode)) {
    identifyingCodeError.value = true;
    $message.error('验证码格式不正确，请重新输入！');
  } else {
    identifyingCodeError.value = false;
  }
};
// 密码验证规则
const validatePassword = () => {
  if (!form.password) {
    passwordError.value = true;
    $message.errors('密码不能为空');
  } else {
    passwordError.value = false;
  }
};

// 确认密码验证规则
const validateConfirmPassword = () => {
  if (!form.secondPassword) {
    secondPasswordError.value = true;
    $message.errors('请再次输入密码');
  } else {
    secondPasswordError.value = false;
  }
};
// 表单是否有效
const isFormValid = computed(() => {
  return (
    !accountError.value &&
    !identifyingCodeError.value &&
    !passwordError.value &&
    !secondPasswordError.value &&
    form.account &&
    form.identifyingCode &&
    form.password &&
    form.secondPassword
  );
});

// 提交数据
async function handleSubmit() {
  if (!isFormValid.value) {
    return false;
  }
  const returnData = await resetPassword({
    userName: form.account,
    code: form.identifyingCode,
    uuid,
    password: form.password,
  });
  if (returnData?.code === 200) {
    $message.success('修改成功');
    await router.push({ path: '/login' });
  } else {
    $message.error(returnData?.msg);
  }
}

// 返回登录页
function goBackLogin() {
  router.push({ path: '/login' });
}
</script>

<template>
  <div class="forget-password-box">
    <div class="head-box">
      <div class="left-content">论文投稿排版系统</div>
    </div>
    <div class="main-content">
      <div class="go-back-box">
        <el-button type="primary" @click="goBackLogin">返回登录页</el-button>
      </div>
      <div class="content-title">
        <span>重置密码</span>
        <div class="line"></div>
      </div>
      <div class="form-box">
        <div class="each-form-box">
          <div class="label">手机<span class="red">*</span></div>
          <div class="account-box login-form-box" :class="{ error: accountError }">
            <img src="../../assets/images/common/account-icon.png" alt="" />
            <el-input
              v-model="form.account"
              placeholder="请输入手机号"
              @input="setInputError('account')"
              @blur="validatePhone"
            />
          </div>
        </div>
        <div class="each-form-box">
          <div class="label"></div>
          <div class="code-box">
            <div class="login-form-box" :class="{ error: identifyingCodeError }">
              <img src="../../assets/images/register/email-icon.png" alt="" />
              <el-input
                v-model="form.identifyingCode"
                placeholder="请输入验证码"
                @input="setInputError('identifyingCode')"
                @blur="validateSmsCode"
              />
            </div>
            <el-button @click="sendCode" :disabled="!sendCodeAgain">{{ codeWord }}</el-button>
          </div>
        </div>
        <div class="each-form-box">
          <div class="label">密码<span class="red">*</span></div>
          <div class="password-box login-form-box" :class="{ error: passwordError }">
            <img src="../../assets/images/common/password-icon.png" alt="" />
            <el-input
              v-model="form.password"
              placeholder="请输入密码"
              type="password"
              @input="setInputError('password')"
              @blur="validatePassword"
            />
          </div>
        </div>
        <div class="each-form-box">
          <div class="label">确认密码<span class="red">*</span></div>
          <div class="password-box login-form-box" :class="{ error: secondPasswordError }">
            <img src="../../assets/images/common/password-icon.png" alt="" />
            <el-input
              v-model="form.secondPassword"
              placeholder="二次确认密码"
              type="password"
              @input="setInputError('secondPassword')"
              @blur="validateConfirmPassword"
            />
          </div>
        </div>
      </div>
      <div
        class="submit-btn"
        :class="{ 'submit-btn-disabled': !isFormValid }"
        @click="handleSubmit"
      >
        提交
      </div>
    </div>
  </div>
</template>

<style scoped lang="less">
@import './forgetPassword.less';
</style>
